package models

import (
	"diancan/dao"
	"strconv"
	"sync"
)

type AllBusinessOutlets struct {
	Id int `json:"id" gorm:"column:id"`
	Position string `json:"position" `
	BranchName string `json:"branchName" gorm:"column:branchName"`
	ContractTel string `json:"contract_tel" gorm:"column:contractTel"`
	Longitude string `json:"longitude" gorm:"column:longitude"`
	Latitude string `json:"latitude" gorm:"column:latitude"`
}

var sw sync.WaitGroup

func QueryAllBusinessOutlets() (mAll *[]AllBusinessOutlets,err error) {

	strSql := `select id,position,branchName,longitude,latitude,contractTel from carRentalOutlets`
	var mAllBusinessOutlets []AllBusinessOutlets
	erre := dao.DB.Raw(strSql).Scan(&mAllBusinessOutlets).Error
	if erre != nil {
		return nil,erre
	}
	//查询数据库所有营业网点数据，插入到redis里面，以便于下次用户直接访问的时候就从redis里面取
	dao.RedisMConfig.SetCache("allBusinessOutlets",mAllBusinessOutlets,0)
	//用户获取全部营业网点的时候将数据库的数据查询出来后，遍历插入到redis中,以便于后面的附近营业网点接口的时候需要用到
	for i := 0; i < len(mAllBusinessOutlets); i++ {
		sw.Add(1)
		go insert(i,mAllBusinessOutlets)
	}
	return &mAllBusinessOutlets,nil
}

func insert(i int,mAllBusinessOutlets []AllBusinessOutlets) {
	Longitude, _ := strconv.ParseFloat(mAllBusinessOutlets[i].Longitude, 64)
	Latitude, _ := strconv.ParseFloat(mAllBusinessOutlets[i].Latitude, 64)
	err := dao.RedisMConfig.NewAddNear(mAllBusinessOutlets[i].Position+mAllBusinessOutlets[i].BranchName, Longitude, Latitude)
	if err == nil {
		return
	}
	sw.Done()
}